package com.yfqy.admin.security.login;

import cn.hutool.json.JSONUtil;
import com.yfqy.admin.constant.MyConstants;
import com.yfqy.admin.domain.vo.common.ResultVOBuilder;
import com.yfqy.admin.domain.vo.common.ResultVO;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: 梁二东
 * @Date: 2025/5/6 16:37
 * @Description:
 **/
@Component
public class LoginFailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        String errorMessage = exception.getMessage();
        response.setContentType(MyConstants.CHARSET_UTF8);
        PrintWriter writer = response.getWriter();
        ResultVO responseData = ResultVOBuilder.aResult()
                .data(null)
                .code(500)
                .msg(errorMessage)
                .build();
        writer.print(JSONUtil.toJsonStr(responseData));
        writer.flush();
        writer.close();
    }
}